//
//  HomeViewController.m
//  AILock
//
//  Created by 谭亚明on 2020/6/17.
//  Copyright © 2020 tym. All rights reserved.
//

#import "HomeViewController.h"
#import "Sizes.h"
#import "WellcomViewController.h"
#import "EquipmentRepairVC.h"
#import "WebViewController.h"
#import "UIButton+Badge.h"
#import "UIButton+Gradient.h"
#import "UIButton+ImageTitleSpacing.h"
#import "FamilyManageVC.h"
#import "Colors.h"
#import "HomeEqumentVC.h"
#import "HomeRoomVC.h"
#import "UserTool.h"
#import "UserModel.h"
#import "ESPTools.h"
#import "UserMessageService.h"
#import "Masonry.h"
#import "FamilyChangeView.h"
#import "AddDeviceViewController.h"
#import "UIButton+ImageTitleSpacing.h"
#import "Sizes.h"
#import "MessageVC.h"
#import "Fonts.h"
#import "FamilyService.h"
#import "ZJScrollPageView.h"
#import "AFNetworking.h"
#import "UIColor+HXExtension.h"
#import "TYMButton.h"
#import "UIView+ZFFrame.h"
#import "WXApi.h"
@interface HomeViewController ()<ZJScrollPageViewDelegate>
@property(weak, nonatomic)  ZJScrollPageView     *scrollPageView;
@property(strong, nonatomic)NSArray<NSString *>  *titles;
@property (nonatomic, strong) HomeEqumentVC  *equmentVC;
@property (nonatomic, strong) HomeRoomVC *roomVC;

@property(nonatomic,weak) TYMButton *failyBtn;

@property(nonatomic,weak) TYMButton *mesBtn;
@property(nonatomic,weak) TYMButton *installBtn;

@property(nonatomic,strong) FamilyService *familyService;
@property(nonatomic,strong) UserMessageService *messgeServices;
@property(nonatomic,assign) NSUInteger equmentCount;
@property(nonatomic,assign) NSUInteger roomCount;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initBtns];
    [self initScrollView];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController navigationController:self.navigationController willShowViewController:self animated:YES];
    
    if ([UserTool getCurrentFamily]) {
        NSString *familStr = [NSString stringWithFormat:@"%@的家",[UserTool getCurrentFamily].familyName];
        [self.failyBtn setTitle:familStr forState:UIControlStateNormal];
        [self.failyBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:3];
        [self.equmentVC getFamilyinfofindfamilyequipments];
        [self.roomVC getFamilyRoomsData];
        [self getUnReadUnmber];
    }else{
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showLoginView" object:nil];
        
    }
}

-(UserMessageService*)messgeServices{
    if (_messgeServices == nil) {
        _messgeServices = [[UserMessageService alloc] init];
    }
    return _messgeServices;
}

-(void)getUnReadUnmber{
    if ([UserTool getLogInUser] == nil) {
        return;
    }
    TYMWeak(self);
    [self.messgeServices getUnreadnumFamilyId:[UserTool getCurrentFamily].familyId completion:^(LMJBaseResponse *respon) {
        if ([respon.responseObject[@"data"] integerValue] > 0) {
            [weakself.mesBtn showRed];
        }else{
            [weakself.mesBtn hiddenRed];
        }
    }];
}

-(void)initScrollView{
    self.titles = @[@"设备(0)", @"房间(0)"];
    ZJSegmentStyle *style = [[ZJSegmentStyle alloc] init];
    style.titleFont = Font_Regular(16);
    style.selectedTitleFont = Font_Medium(16);
    style.showLine = YES;
    style.scrollLineHeight = 3;
    style.coverBackgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.39];
    style.coverCornerRadius = 15;
    style.coverHeight = 30;
    style.showCover = YES;
    style.scrollLineColor = [rgbaa(0,0,0,0) colorWithAlphaComponent:0];
    style.segmentHeight = 33;
    style.segmentViewBounces = NO;
    style.normalTitleColor = rgba(255, 255, 255) ;
    style.selectedTitleColor = rgba(255, 255, 255);
    style.contentViewBounces = NO;
    style.adjustCoverOrLineWidth = YES;
    style.autoAdjustTitlesWidth = YES;
    
    ZJScrollPageView *scrollPageView = [[ZJScrollPageView alloc] initWithFrame:CGRectMake(0,85+SafeTopMargin, ScreenWidth, ScreenHeight - 85-SafeTopMargin-TabbarHeight) segmentStyle:style titles:self.titles parentViewController:self delegate:self];
    [scrollPageView bringSubviewToFront:scrollPageView.segmentView];
    scrollPageView.contentView.frame = CGRectMake(0, 35, ScreenWidth, ScreenHeight - 85-SafeTopMargin-TabbarHeight-10-35);
    UIView *colorLine = [[UIView alloc] initWithFrame:CGRectZero];
    colorLine.backgroundColor = [UIColor whiteColor];
    [scrollPageView.segmentView.scrollLine addSubview:colorLine];
    [colorLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(scrollPageView.segmentView.scrollLine);
        make.size.mas_equalTo(CGSizeMake(14, 3.5));
    }];
    scrollPageView.segmentView.backgroundColor = [UIColor clearColor];
    scrollPageView.contentView.backgroundColor = [UIColor clearColor];
    scrollPageView.contentView.collectionView.backgroundColor = [UIColor clearColor];
    scrollPageView.backgroundColor = [UIColor clearColor];
    [scrollPageView setSelectedIndex:0 animated:NO];
    self.scrollPageView = scrollPageView;
    [self.view addSubview:self.scrollPageView];
}

//ZJScrollViewDelegate
- (NSInteger)numberOfChildViewControllers{
    return self.titles.count;
}

-(FamilyService*)familyService{
    if (_familyService == nil) {
        _familyService = [[FamilyService alloc] init];
    }
    return _familyService;;
}

- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    if (index == 0) {
        return self.equmentVC;
    } else if (index == 1) {
        return self.roomVC;
    }
    return nil;
}

-(HomeEqumentVC*)equmentVC{
    if (_equmentVC == nil) {
        _equmentVC = [[HomeEqumentVC alloc] init];
        _equmentVC.presentVC = self;
        TYMWeak(self);
        _equmentVC.homeEqumentCountBlock = ^(NSInteger dataCount) {
            weakself.equmentCount = dataCount;
            [weakself updateSegmentTitles];
        };
    }
    return _equmentVC;
}

-(void)updateSegmentTitles{
    
    NSArray *titlesArray = @[[NSString stringWithFormat:@"设备(%ld)",self.equmentCount],[NSString stringWithFormat:@"房间(%ld)",self.roomCount]];
    [self.scrollPageView.segmentView reloadTitlesWithNewTitles:titlesArray];
}

-(HomeRoomVC*)roomVC{
    if (_roomVC == nil) {
        _roomVC = [[HomeRoomVC alloc] init];
        TYMWeak(self);
        
        _roomVC.homeRootCountBlock = ^(NSInteger dataCount) {
            weakself.roomCount = dataCount;
            [weakself updateSegmentTitles];
        };
    }
    return _roomVC;
}



-(void)initBtns{
    
    
    float btnW = 28;
    
    TYMButton *installBtn = [TYMButton btn_text:@"安装" image:@"icon_anzhuang" color:[UIColor whiteColor] font:Font_Regular(13)];
    installBtn.frame = CGRectMake(ScreenWidth/2, 32.5+SafeTopMargin,67, 28);
    [installBtn gradientButtonWithSize:CGSizeMake(74, 28) colorArray:@[(id)rgba(76, 132, 255),(id)rgba(139, 175, 255)] percentageArray:@[@(0.5),@(1)] gradientType:GradientFromLeftTopToRightBottom];
    [self.view addSubview:installBtn];
    [installBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:2];
    [installBtn addTarget:self action:@selector(installAction:) forControlEvents:UIControlEventTouchUpInside];
    installBtn.layer.masksToBounds = YES;
    installBtn.layer.cornerRadius = 14;
    self.installBtn = installBtn;
    
    TYMButton *repairBtn = [TYMButton btn_text:@"维修" image:@"icon_weixiu" color:[UIColor whiteColor] font:Font_Regular(13)];
    repairBtn.frame = CGRectMake(installBtn.zf_right+10, 32.5+SafeTopMargin,67, 28);
    [repairBtn gradientButtonWithSize:CGSizeMake(74, 28) colorArray:@[(id)rgba(246, 152, 29),(id)rgba(253, 203, 33)] percentageArray:@[@(0.5),@(1)] gradientType:GradientFromLeftTopToRightBottom];
    [self.view addSubview:repairBtn];
    [repairBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:2];
    [repairBtn addTarget:self action:@selector(repairAction:) forControlEvents:UIControlEventTouchUpInside];
    repairBtn.layer.masksToBounds = YES;
    repairBtn.layer.cornerRadius = 14;
    
    
    TYMButton *messBtn = [TYMButton btn_Image:@"icon_nav_measage"];
    [self.view addSubview:messBtn];
    [messBtn addTarget:self action:@selector(messageFunc:) forControlEvents:UIControlEventTouchUpInside];
    messBtn.frame = CGRectMake(ScreenWidth-15-btnW, installBtn.zf_y, btnW, btnW);
    self.mesBtn = messBtn;
   // [self.mesBtn showRed];
    
    TYMButton *failyBtn = [TYMButton btn_text:@"familyBtn" image:@"icon_more3" color:[UIColor whiteColor] font:Font_Medium(16)];
    [failyBtn addTarget:self action:@selector(failyBtnFunc:) forControlEvents:UIControlEventTouchUpInside];
    failyBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.failyBtn = failyBtn;
    [self.view addSubview:failyBtn];
    [self.failyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(45);
        make.top.mas_equalTo(installBtn.zf_y);
        make.height.mas_equalTo(btnW);
        make.width.mas_lessThanOrEqualTo(ScreenWidth/2-30);
       // make.right.mas_lessThanOrEqualTo(self.installBtn.mas_left);
    }];
    UIImageView *homeImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_jia"]];
    homeImage.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:homeImage];
    
    [homeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.mas_equalTo(failyBtn);
    }];
}



//TODO: 家庭选择
-(void)failyBtnFunc:(UIButton*)btn{
    TYMWeak(self);
    [FamilyChangeView showFamilyChangeViewcompletion:^(NSInteger actionType) {
        if (actionType == -1) {
            FamilyManageVC *manageVC = [[FamilyManageVC alloc] init];
            [weakself.navigationController pushViewController:manageVC animated:YES];
        }else{
            [self viewWillAppear:YES];
        }
    }];
    
}

//维修
-(void)repairAction:(id)sender{
    
    if (![WXApi isWXAppInstalled]) {
        [WHToast showMessage:@"无法调用小程序" duration:2 finishHandler:nil];
        return;
    }
    
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = @"gh_0299e0221ca8";  //拉起的小程序的username
    launchMiniProgramReq.path = @"/pages/service/service";    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
    
#ifdef DEBUG
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypePreview; //拉起小程序的类型
#else
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
#endif
    
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
       
    }];
    
//    EquipmentRepairVC *repairVC = [[EquipmentRepairVC alloc] init];
//    [self.navigationController pushViewController:repairVC animated:YES];
}

//安装
-(void)installAction:(id)sender{
    
//    WebViewController *webView = [[WebViewController alloc] init];
//    NSString *url = [NSString stringWithFormat:@"%@?mobile=%@",RepairUrl,[UserTool getLogInUser].mobile];
//    webView.gotoURL = url;
//    webView.titleStr = @"预约安装";
//    [self.navigationController pushViewController:webView animated:YES];
    
    if (![WXApi isWXAppInstalled]) {
        [WHToast showMessage:@"无法调用小程序" duration:2 finishHandler:nil];
        return;
    }
    
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = @"gh_0299e0221ca8";  //拉起的小程序的username
    launchMiniProgramReq.path = @"/pages/install/install";    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
#ifdef DEBUG
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypePreview; //拉起小程序的类型
#else
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
#endif
    //[WXApi sendReq:launchMiniProgramReq];
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
       
    }];
    
}

//TODO: 消息
-(void)messageFunc:(UIButton*)btn{
    
    MessageVC *messageVC = [[MessageVC alloc] init];
    [self.navigationController pushViewController:messageVC animated:YES];
}



@end
